<?php


namespace App\Service;


use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;

class GameApiService
{

    //天行数据

    private $API_KEY = '81c7b575c1ff709d718b8bd4689d73ea';
    private $API_URL = 'http://api.tianapi.com';


    /**
     * @Inject()
     * @var StdoutLoggerInterface
     */
    protected $console;

    /**
     * @Inject
     * @var ClientFactory
     */
    protected $clientFactory;

    //获取成语信息
    public function getCYInfo($word): ?array
    {
        return $this->apiRequest('txapi/chengyu/index', ['word' => $word]);
    }

    //成语接龙
    public function CYJL($word, $user_id = ''): ?array
    {
        return $this->apiRequest('txapi/chengyujielong/index', ['word' => $word, 'userid' => $user_id]);
    }

    //土味情话
    public function loveSay(): ?array
    {
        return $this->apiRequest('txapi/saylove/index');
    }

    //彩虹屁
    public function caihongp(): ?array
    {
        return $this->apiRequest('txapi/caihongpi/index');
    }

    //星座运势
    public function starZ($star): ?array
    {
        return $this->apiRequest('txapi/star/index', ['astro' => $star]);
    }

    //吉凶测试
    public function jixiong()
    {
        return $this->apiRequest('txapi/jixiong/index', ['number' => (int)microtime(true)]);
    }


    /**
     * API请求
     * @param $uri
     * @param array $query
     * @return array|null
     */
    protected function apiRequest($uri, array $query = []): ?array
    {
        $option = [
            'base_uri' => $this->API_URL,
        ];
        $option['query'] = array_merge(['key' => $this->API_KEY], $query);
        $client = $this->clientFactory->create($option);
        try {
            $response = $client->get($uri);
            $result = $response->getBody()->getContents();
            return @json_decode($result, true);
        } catch (GuzzleException $e) {
            $this->console->error('获取失败！'.$e->getMessage());
        }
        return null;
    }
}